from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from six_it.models import Article
from xyz.serializers.article import ArticleInfoSerializer


class ArticlelInfoView(ListAPIView):
    def get_queryset(self):
        id = self.kwargs.get('id')
        if id == '-1':
            return Article.objects.all()
        else:
            return Article.objects.filter(channel=id)

    serializer_class = ArticleInfoSerializer


class ArticlelCollectView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request, id):
        article = Article.objects.get(id=id)
        user_ids = article.collected_users.all()
        if request.user in user_ids:
            article.collected_users.remove(request.user)
            article.save()
            return Response({
                'message': '取消收藏成功',
                'success': True
            })
        else:
            article.collected_users.add(request.user)
            article.save()
            return Response({
                'message': '收藏成功',
                'success': True
            })
